<template>
  <div class="app-container">
    <el-card class="filter-container" shadow="never">
      <div>
        <i class="el-icon-search"></i>
        <span>筛选搜索</span>
        <el-button style="float:right" type="primary" @click="handleAdd" size="small">
          充值
        </el-button>
      </div>
      <div style="margin-top: 15px">
        <el-form :inline="true" :model="listQuery" size="small" label-width="140px">
          <el-form-item label="所属机构：">
            <el-select v-model="listQuery.merchant_id" placeholder="请选择机构" clearable>
              <el-option v-for="item in merchantList" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="充值时间：">
            <el-date-picker v-model="dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>
          <el-button size="mini" type="primary" @click="handleSearchList()">查询</el-button>
        </el-form>
      </div>
    </el-card>
    <div class="table-container">
      <el-table ref="rechargeTable" :data="list" style="width: 100%;" v-loading="listLoading" border>
        <el-table-column label="编号" width="100" align="center">
          <template slot-scope="scope">{{ scope.row.id }}</template>
        </el-table-column>
        <el-table-column label="所属机构" align="center">
          <template slot-scope="scope">{{ scope.row.merchant_name }}</template>
        </el-table-column>
        <el-table-column label="充值数量" align="center">
          <template slot-scope="scope">
            <span style="color: #67C23A; font-weight: bold;">{{ scope.row.amount }}</span>
          </template>
        </el-table-column>
        <el-table-column label="充值前余额" align="center">
          <template slot-scope="scope">{{ scope.row.before_balance }}</template>
        </el-table-column>
        <el-table-column label="充值后余额" align="center">
          <template slot-scope="scope">{{ scope.row.after_balance }}</template>
        </el-table-column>
        <el-table-column label="操作人" align="center">
          <template slot-scope="scope">{{ scope.row.operator }}</template>
        </el-table-column>
        <el-table-column label="充值时间" align="center" width="180">
          <template slot-scope="scope">{{ scope.row.created_at }}</template>
        </el-table-column>
        <el-table-column label="备注" align="center">
          <template slot-scope="scope">{{ scope.row.note }}</template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
        layout="total, sizes,prev, pager, next,jumper" :page-size="listQuery.pageSize" :page-sizes="[5, 10, 15]"
        :current-page.sync="listQuery.pageNum" :total="total">
      </el-pagination>
    </div>

    <!-- 充值对话框 -->
    <el-dialog title="充值沐浴露" :visible.sync="dialogVisible" width="500px">
      <div style="margin-bottom: 20px" v-loading="balanceLoading">
        <span style="font-size: 14px; color: #606266">当前沐浴露余额</span>
        <span style="font-size: 24px; font-weight: bold; color: #409EFF; margin-left: 20px">
          {{ currentBalance }}包
        </span>
      </div>
      <el-form :model="recharge" :rules="rules" ref="rechargeForm" label-width="120px">
        <el-form-item label="所属机构：" prop="merchant_id" v-if="!$route.query.merchant_id">
          <el-select v-model="recharge.merchant_id" placeholder="请选择机构" style="width: 100%"
            @change="handleMerchantChange">
            <el-option v-for="item in merchantList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="充值沐浴露：" prop="amount">
          <el-input v-model="recharge.amount" type="number" placeholder="请输入充值数量">
            <template slot="append">包</template>
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确认充值</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList as fetchMerchantList, recharge, fetchRechargeList, getMerchant } from '@/api/merchant'

export default {
  name: 'merchantRechargeList',
  data() {
    return {
      listQuery: {
        merchant_id: null,
        start_date: null,
        end_date: null,
        pageNum: 1,
        pageSize: 10
      },
      dateRange: null,
      list: [],
      total: 0,
      listLoading: false,
      merchantList: [],
      dialogVisible: false,
      submitLoading: false,
      balanceLoading: false,
      recharge: {
        merchant_id: null,
        amount: null,
        note: ''
      },
      currentBalance: 0,
      rules: {
        merchant_id: [
          { required: true, message: '请选择所属机构', trigger: 'change' }
        ],
        amount: [
          { required: true, message: '请输入充值数量', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getMerchantList()
    this.getList()
  },
  methods: {
    getMerchantList() {
      fetchMerchantList({ pageSize: 100 }).then(response => {
        this.merchantList = response.data.data
      })
    },
    getList() {
      this.listLoading = true
      // 构建查询参数，使用 page 而不是 pageNum
      const params = {
        merchant_id: this.listQuery.merchant_id,
        start_date: this.listQuery.start_date,
        end_date: this.listQuery.end_date,
        page: this.listQuery.pageNum,
        pageSize: this.listQuery.pageSize
      }
      fetchRechargeList(params).then(response => {
        this.listLoading = false
        this.list = response.data.data
        this.total = response.data.total
      }).catch(() => {
        this.listLoading = false
      })
    },
    handleSearchList() {
      if (this.dateRange && this.dateRange.length === 2) {
        // 开始时间带上 00:00:00，结束时间带上 23:59:59
        this.listQuery.start_date = this.formatDate(this.dateRange[0], true)
        this.listQuery.end_date = this.formatDate(this.dateRange[1], false)
      } else {
        this.listQuery.start_date = null
        this.listQuery.end_date = null
      }
      this.listQuery.pageNum = 1
      this.getList()
    },
    formatDate(date, isStart = true) {
      if (!date) return null
      const d = new Date(date)
      const year = d.getFullYear()
      const month = String(d.getMonth() + 1).padStart(2, '0')
      const day = String(d.getDate()).padStart(2, '0')
      // 开始时间带上 00:00:00，结束时间带上 23:59:59
      const time = isStart ? '00:00:00' : '23:59:59'
      return `${year}-${month}-${day} ${time}`
    },
    handleResetSearch() {
      this.listQuery = {
        merchant_id: null,
        start_date: null,
        end_date: null,
        pageNum: 1,
        pageSize: 10
      }
      this.dateRange = null
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.pageNum = 1
      this.listQuery.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.pageNum = val
      this.getList()
    },
    handleAdd() {
      this.recharge = {
        merchant_id: null,
        amount: null,
        type: 3,
        note: ''
      }
      this.currentBalance = 0
      this.dialogVisible = true
    },
    handleMerchantChange(merchantId) {
      if (merchantId) {
        // 显示loading提示
        this.balanceLoading = true
        this.currentBalance = 0
        // 调用接口获取机构详情，包括余额
        getMerchant(merchantId).then(response => {
          this.balanceLoading = false
          this.currentBalance = response.data.balance || 0
        }).catch(() => {
          this.balanceLoading = false
          this.currentBalance = 0
          this.$message.error('获取机构余额失败')
        })
      } else {
        this.currentBalance = 0
        this.balanceLoading = false
      }
    },
    handleSubmit() {
      this.$refs.rechargeForm.validate((valid) => {
        if (valid) {
          if (this.recharge.amount <= 0) {
            this.$message.error('充值数量必须大于0')
            return
          }
          this.submitLoading = true
          recharge(this.recharge.merchant_id, this.recharge).then(() => {
            this.submitLoading = false
            this.$message({
              type: 'success',
              message: '充值成功!'
            })
            this.dialogVisible = false
            this.getList()
          }).catch(() => {
            this.submitLoading = false
          })
        }
      })
    }
  }
}
</script>

<style scoped></style>
